import pygame
import sys
import os
import random
from chess_board import ChessBoard
from chess_pieces import create_initial_pieces
from game_rules import GameRules
from game_state import GameState

# 初始化PyGame
pygame.init()
pygame.mixer.init()  # 初始化音频模块

# 常量定义
DEFAULT_WINDOW_WIDTH = 850  # 默认窗口宽度
DEFAULT_WINDOW_HEIGHT = 850  # 默认窗口高度
LEFT_PANEL_WIDTH_RATIO = 130 / 850  # 左侧面板宽度比例
BOARD_MARGIN_TOP_RATIO = 50 / 850  # 棋盘顶部边距比例
FPS = 60

# 颜色定义
BACKGROUND_COLOR = (240, 217, 181)  # 更温暖的背景色
PANEL_COLOR = (230, 210, 185)       # 面板背景色
PANEL_BORDER = (160, 140, 110)      # 面板边框色
BLACK = (0, 0, 0)
RED = (180, 30, 30)  # 更深的红色
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
POPUP_BG = (240, 240, 240)
BUTTON_COLOR = (100, 100, 200)
BUTTON_HOVER = (120, 120, 220)
BUTTON_TEXT = (240, 240, 255)
GOLD = (218, 165, 32)
LAST_MOVE_SOURCE = (0, 200, 80, 100)      # 上一步起点颜色（绿色半透明）
LAST_MOVE_TARGET = (0, 200, 80, 150)      # 上一步终点颜色（绿色半透明但更深）

# 游戏模式
MODE_PVP = "pvp"  # 人人对战
MODE_PVC = "pvc"  # 人机对战

# 玩家阵营
CAMP_RED = "red"   # 玩家执红
CAMP_BLACK = "black"  # 玩家执黑

# 获取当前文件目录，用于定位音效文件
current_dir = os.path.dirname(os.path.abspath(__file__))
sounds_dir = os.path.join(current_dir, "sounds")

# 加载音效
try:
    # 使用完整路径加载音效
    check_sound_path = os.path.join(sounds_dir, "check.wav")
    move_sound_path = os.path.join(sounds_dir, "move.wav")
    capture_sound_path = os.path.join(sounds_dir, "capture.wav")
    
    CHECK_SOUND = pygame.mixer.Sound(check_sound_path)
    MOVE_SOUND = pygame.mixer.Sound(move_sound_path)
    CAPTURE_SOUND = pygame.mixer.Sound(capture_sound_path)
    
    # 设置音量（值范围0.0到1.0）
    CHECK_SOUND.set_volume(0.8)  # 将军音效音量设为80%
    MOVE_SOUND.set_volume(0.6)   # 移动音效音量设为60%
    CAPTURE_SOUND.set_volume(0.7) # 吃子音效音量设为70%
except Exception as e:
    # 如果找不到音效文件，创建空声音对象
    CHECK_SOUND = pygame.mixer.Sound(bytes(bytearray(100)))
    MOVE_SOUND = pygame.mixer.Sound(bytes(bytearray(100)))
    CAPTURE_SOUND = pygame.mixer.Sound(bytes(bytearray(100)))
    # 设置音量为0（无声）
    CHECK_SOUND.set_volume(0)
    MOVE_SOUND.set_volume(0)
    CAPTURE_SOUND.set_volume(0)
    print(f"警告：未能加载音效文件。错误: {e}")

# 绘制背景函数
def draw_background(surface):
    """绘制统一的背景纹理"""
    # 填充基础背景色
    surface.fill(BACKGROUND_COLOR)
    
    # 添加纹理效果
    for i in range(0, surface.get_width(), 10):
        for j in range(0, surface.get_height(), 10):
            if (i + j) % 20 == 0:
                pygame.draw.rect(surface, (230, 207, 171), (i, j, 5, 5))

class Avatar:
    """玩家头像框类"""
    def __init__(self, x, y, radius, color, player_name, is_red=True):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.player_name = player_name
        self.is_red = is_red
        self.active = False  # 是否是当前活跃玩家
        
        # 加载飘逸字体 - 尝试加载几种可能的字体
        self.update_font()
        
    def update_font(self):
        """根据当前头像尺寸更新字体"""
        self.piece_font = None
        font_options = [
            'KaiTi', 'STKaiti', '楷体', 'SimKai', 
            'FangSong', 'STFangsong', '仿宋', 
            'STXingkai', '华文行楷',
            'LiSu', '隶书'
        ]
        
        for font_name in font_options:
            try:
                self.piece_font = pygame.font.SysFont(font_name, int(self.radius * 1.2), bold=True)
                break
            except:
                continue
                
        # 如果没有找到合适的飘逸字体，使用默认字体
        if not self.piece_font:
            self.piece_font = pygame.font.SysFont('SimHei', int(self.radius * 1.2), bold=True)
        
        # 名称字体使用普通字体
        self.name_font = pygame.font.SysFont('SimHei', 18)
        
    def draw(self, screen):
        # 绘制外圆框
        border_color = (200, 100, 100) if self.is_red else (60, 60, 80)
        border_width = 3 if self.active else 1
        
        # 如果是当前活跃玩家，添加光晕效果
        if self.active:
            # 绘制光晕
            for i in range(5):
                glow_radius = self.radius + 3 + i
                alpha = 100 - i * 20
                glow_color = (255, 50, 50, alpha) if self.is_red else (50, 50, 100, alpha)
                glow_surface = pygame.Surface((glow_radius*2, glow_radius*2), pygame.SRCALPHA)
                pygame.draw.circle(glow_surface, glow_color, (glow_radius, glow_radius), glow_radius, 2)
                screen.blit(glow_surface, (self.x - glow_radius, self.y - glow_radius))
        
        # 绘制头像背景
        pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
        pygame.draw.circle(screen, border_color, (self.x, self.y), self.radius, border_width)
        
        # 绘制简单的玩家标识
        if self.is_red:
            # 红方标识 - 绘制"帅"字或简单图案
            text = "帅"
            text_color = (180, 30, 30)
        else:  # black
            # 黑方标识 - 绘制"将"字或简单图案
            text = "将"
            text_color = (30, 30, 30)
        
        # 添加文字阴影效果，提高可读性
        shadow_color = (120, 20, 20) if self.is_red else (10, 10, 10)
        shadow_offset = 1
        
        # 先绘制阴影
        text_shadow = self.piece_font.render(text, True, shadow_color)
        text_shadow_rect = text_shadow.get_rect(center=(self.x + shadow_offset, self.y + shadow_offset))
        screen.blit(text_shadow, text_shadow_rect)
        
        # 再绘制文字
        text_surface = self.piece_font.render(text, True, text_color)
        text_rect = text_surface.get_rect(center=(self.x, self.y))
        screen.blit(text_surface, text_rect)
        
        # 绘制玩家名称
        name_surface = self.name_font.render(self.player_name, True, (20, 20, 20))
        name_rect = name_surface.get_rect(center=(self.x, self.y + self.radius + 20))
        screen.blit(name_surface, name_rect)
        
    def set_active(self, active):
        """设置是否是当前活跃玩家"""
        self.active = active
        
    def update_position(self, x, y, radius=None):
        """更新头像位置和大小"""
        self.x = x
        self.y = y
        if radius:
            self.radius = radius
            self.update_font()  # 如果大小变化，需要更新字体

class Button:
    def __init__(self, x, y, width, height, text, font_size=24):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.font = pygame.font.SysFont('SimHei', font_size)
        self.is_hovered = False
        
    def draw(self, screen):
        # 绘制按钮（带悬停效果）
        color = BUTTON_HOVER if self.is_hovered else BUTTON_COLOR
        pygame.draw.rect(screen, color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 2)  # 边框
        
        # 绘制文本
        text_surface = self.font.render(self.text, True, BUTTON_TEXT)
        text_rect = text_surface.get_rect(center=self.rect.center)
        screen.blit(text_surface, text_rect)
        
    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)
        return self.is_hovered
    
    def is_clicked(self, pos, event):
        if event.type == pygame.MOUSEBUTTONDOWN and self.rect.collidepoint(pos):
            return True
        return False

class ModeSelectionScreen:
    def __init__(self):
        # 初始化窗口尺寸和模式
        self.window_width = DEFAULT_WINDOW_WIDTH
        self.window_height = DEFAULT_WINDOW_HEIGHT
        self.is_fullscreen = False
        self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        pygame.display.set_caption("中国象棋 - 模式选择")
        
        self.update_layout()
        self.selected_mode = None
        
    def update_layout(self):
        """根据当前窗口尺寸更新布局"""
        button_width = 300
        button_height = 80
        button_spacing = 40
        center_x = self.window_width // 2
        center_y = self.window_height // 2
        
        # 创建按钮
        self.pvp_button = Button(
            center_x - button_width // 2,
            center_y - button_height - button_spacing // 2,
            button_width,
            button_height,
            "双人对战",
            32
        )
        
        self.pvc_button = Button(
            center_x - button_width // 2,
            center_y + button_spacing // 2,
            button_width,
            button_height,
            "人机对战",
            32
        )
    
    def toggle_fullscreen(self):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        
        if self.is_fullscreen:
            # 获取显示器信息
            info = pygame.display.Info()
            # 保存窗口模式的尺寸
            self.windowed_size = (self.window_width, self.window_height)
            # 切换到全屏模式
            self.screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
            self.window_width = info.current_w
            self.window_height = info.current_h
        else:
            # 恢复窗口模式
            self.window_width, self.window_height = self.windowed_size
            self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        
        # 更新布局
        self.update_layout()
        
    def handle_resize(self, new_size):
        """处理窗口大小变化"""
        self.window_width, self.window_height = new_size
        # 更新布局
        self.update_layout()
        
    def run(self):
        """运行模式选择界面"""
        clock = pygame.time.Clock()
        
        while self.selected_mode is None:
            mouse_pos = pygame.mouse.get_pos()
            
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                
                # 处理窗口大小变化
                if event.type == pygame.VIDEORESIZE:
                    if not self.is_fullscreen:  # 只在窗口模式下处理大小变化
                        self.handle_resize((event.w, event.h))
                
                # 处理键盘事件
                if event.type == pygame.KEYDOWN:
                    # F11或Alt+Enter切换全屏
                    if event.key == pygame.K_F11 or (
                        event.key == pygame.K_RETURN and 
                        pygame.key.get_mods() & pygame.KMOD_ALT
                    ):
                        self.toggle_fullscreen()
                
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.pvp_button.is_clicked(mouse_pos, event):
                        self.selected_mode = MODE_PVP
                    elif self.pvc_button.is_clicked(mouse_pos, event):
                        self.selected_mode = MODE_PVC
            
            # 更新按钮悬停状态
            self.pvp_button.check_hover(mouse_pos)
            self.pvc_button.check_hover(mouse_pos)
            
            # 绘制界面
            self.draw()
            pygame.display.flip()
            clock.tick(FPS)
        
        return self.selected_mode
    
    def draw(self):
        """绘制选择界面"""
        # 使用统一的背景绘制函数
        draw_background(self.screen)
        
        # 绘制标题
        title_font = pygame.font.SysFont('SimHei', 64)
        title_text = "中国象棋"
        title_surface = title_font.render(title_text, True, BLACK)
        title_rect = title_surface.get_rect(center=(self.window_width//2, 150))
        self.screen.blit(title_surface, title_rect)
        
        # 绘制金色装饰线
        line_y = title_rect.bottom + 20
        pygame.draw.line(
            self.screen, 
            GOLD, 
            (self.window_width//4, line_y), 
            (self.window_width*3//4, line_y), 
            3
        )
        
        # 绘制副标题
        subtitle_font = pygame.font.SysFont('SimHei', 36)
        subtitle_text = "请选择游戏模式"
        subtitle_surface = subtitle_font.render(subtitle_text, True, BLACK)
        subtitle_rect = subtitle_surface.get_rect(center=(self.window_width//2, line_y + 60))
        self.screen.blit(subtitle_surface, subtitle_rect)
        
        # 绘制按钮
        self.pvp_button.draw(self.screen)
        self.pvc_button.draw(self.screen)
        
        # 绘制按钮说明文字
        desc_font = pygame.font.SysFont('SimHei', 18)
        pvp_desc = "两位玩家轮流对弈"
        pvc_desc = "与电脑AI对弈"
        
        pvp_desc_surface = desc_font.render(pvp_desc, True, BLACK)
        pvc_desc_surface = desc_font.render(pvc_desc, True, BLACK)
        
        pvp_desc_rect = pvp_desc_surface.get_rect(
            center=(self.window_width//2, self.pvp_button.rect.bottom + 25)
        )
        pvc_desc_rect = pvc_desc_surface.get_rect(
            center=(self.window_width//2, self.pvc_button.rect.bottom + 25)
        )
        
        self.screen.blit(pvp_desc_surface, pvp_desc_rect)
        self.screen.blit(pvc_desc_surface, pvc_desc_rect)
        
        # 绘制版权信息
        copyright_text = "© 2025 洛伦兹力不做功"
        copyright_surface = desc_font.render(copyright_text, True, (100, 100, 100))
        copyright_rect = copyright_surface.get_rect(
            center=(self.window_width//2, self.window_height - 30)
        )
        self.screen.blit(copyright_surface, copyright_rect)

class PopupDialog:
    def __init__(self, width, height, message, total_time=0, red_time=0, black_time=0):
        self.width = width
        self.height = height
        self.message = message
        self.total_time = total_time
        self.red_time = red_time
        self.black_time = black_time
        
        # 计算弹窗位置 - 会在绘制时动态计算
        self.x = 0
        self.y = 0
        
        # 创建"重新开始"按钮
        button_width = 160
        button_height = 50
        self.button_width = button_width
        self.button_height = button_height
        self.restart_button = None  # 会在绘制时动态创建
        
    def draw(self, screen):
        # 获取当前窗口尺寸
        window_width, window_height = screen.get_size()
        
        # 重新计算弹窗位置
        self.x = (window_width - self.width) // 2
        self.y = (window_height - self.height) // 2
        
        # 更新按钮位置
        button_x = self.x + (self.width - self.button_width) // 2
        button_y = self.y + self.height - self.button_height - 20
        self.restart_button = Button(button_x, button_y, self.button_width, self.button_height, "重新开始")
        
        # 绘制半透明背景
        overlay = pygame.Surface((window_width, window_height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))  # 半透明黑色
        screen.blit(overlay, (0, 0))
        
        # 绘制弹窗主体
        pygame.draw.rect(screen, POPUP_BG, (self.x, self.y, self.width, self.height))
        pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 3)
        
        # 添加装饰边框
        inner_margin = 10
        pygame.draw.rect(
            screen, 
            (180, 180, 180), 
            (self.x + inner_margin, self.y + inner_margin, 
             self.width - 2*inner_margin, self.height - 2*inner_margin), 
            2
        )
        
        # 绘制标题文本
        font_big = pygame.font.SysFont('SimHei', 40)
        text_surface = font_big.render("游戏结束", True, BLACK)
        text_rect = text_surface.get_rect(center=(window_width//2, self.y + 50))
        screen.blit(text_surface, text_rect)
        
        # 绘制结果文本
        font = pygame.font.SysFont('SimHei', 32)
        text_surface = font.render(self.message, True, RED)
        text_rect = text_surface.get_rect(center=(window_width//2, self.y + 110))
        screen.blit(text_surface, text_rect)
        
        # 绘制时间信息
        time_font = pygame.font.SysFont('SimHei', 20)
        
        # 显示总用时
        total_time_str = f"{int(self.total_time//60):02}:{int(self.total_time%60):02}"
        total_time_text = f"对局总时长: {total_time_str}"
        total_time_surface = time_font.render(total_time_text, True, BLACK)
        total_time_rect = total_time_surface.get_rect(center=(window_width//2, self.y + 160))
        screen.blit(total_time_surface, total_time_rect)
        
        # 显示红方用时
        red_time_str = f"{int(self.red_time//60):02}:{int(self.red_time%60):02}"
        red_time_text = f"红方用时: {red_time_str}"
        red_time_surface = time_font.render(red_time_text, True, RED)
        red_time_rect = red_time_surface.get_rect(center=(window_width//2, self.y + 190))
        screen.blit(red_time_surface, red_time_rect)
        
        # 显示黑方用时
        black_time_str = f"{int(self.black_time//60):02}:{int(self.black_time%60):02}"
        black_time_text = f"黑方用时: {black_time_str}"
        black_time_surface = time_font.render(black_time_text, True, BLACK)
        black_time_rect = black_time_surface.get_rect(center=(window_width//2, self.y + 220))
        screen.blit(black_time_surface, black_time_rect)
        
        # 绘制按钮
        self.restart_button.draw(screen)
    
    def handle_event(self, event, mouse_pos):
        # 如果按钮尚未创建，返回False
        if not self.restart_button:
            return False
            
        # 处理鼠标悬停
        self.restart_button.check_hover(mouse_pos)
        
        # 检查按钮点击
        if self.restart_button.is_clicked(mouse_pos, event):
            return True
        return False

class ConfirmDialog:
    def __init__(self, width, height, message):
        self.width = width
        self.height = height
        self.message = message
        
        # 计算弹窗位置 - 会在绘制时动态计算
        self.x = 0
        self.y = 0
        
        # 按钮尺寸
        self.button_width = 120
        self.button_height = 40
        self.button_spacing = 30
        
        # 按钮会在绘制时动态创建
        self.confirm_button = None
        self.cancel_button = None
        
        # 结果
        self.result = None  # None = 未选择, True = 确认, False = 取消
        
    def draw(self, screen):
        # 获取当前窗口尺寸
        window_width, window_height = screen.get_size()
        
        # 重新计算弹窗位置
        self.x = (window_width - self.width) // 2
        self.y = (window_height - self.height) // 2
        
        # 更新按钮位置
        confirm_x = self.x + (self.width // 2) - self.button_width - (self.button_spacing // 2)
        confirm_y = self.y + self.height - self.button_height - 20
        self.confirm_button = Button(confirm_x, confirm_y, self.button_width, self.button_height, "确认")
        
        cancel_x = self.x + (self.width // 2) + (self.button_spacing // 2)
        cancel_y = self.y + self.height - self.button_height - 20
        self.cancel_button = Button(cancel_x, cancel_y, self.button_width, self.button_height, "取消")
        
        # 绘制半透明背景
        overlay = pygame.Surface((window_width, window_height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))  # 半透明黑色
        screen.blit(overlay, (0, 0))
        
        # 绘制弹窗主体
        pygame.draw.rect(screen, POPUP_BG, (self.x, self.y, self.width, self.height))
        pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 3)
        
        # 添加装饰边框
        inner_margin = 10
        pygame.draw.rect(
            screen, 
            (180, 180, 180), 
            (self.x + inner_margin, self.y + inner_margin, 
             self.width - 2*inner_margin, self.height - 2*inner_margin), 
            2
        )
        
        # 绘制标题文本
        font_big = pygame.font.SysFont('SimHei', 36)
        text_surface = font_big.render("确认", True, BLACK)
        text_rect = text_surface.get_rect(center=(window_width//2, self.y + 40))
        screen.blit(text_surface, text_rect)
        
        # 绘制确认信息文本
        font = pygame.font.SysFont('SimHei', 24)
        # 处理消息换行显示
        lines = self.message.split('\n')
        line_height = 30
        start_y = self.y + 90
        
        for i, line in enumerate(lines):
            text_surface = font.render(line, True, BLACK)
            text_rect = text_surface.get_rect(center=(window_width//2, start_y + i * line_height))
            screen.blit(text_surface, text_rect)
        
        # 绘制按钮
        self.confirm_button.draw(screen)
        self.cancel_button.draw(screen)
    
    def handle_event(self, event, mouse_pos):
        # 如果按钮尚未创建，返回None
        if not self.confirm_button or not self.cancel_button:
            return None
            
        # 处理鼠标悬停
        self.confirm_button.check_hover(mouse_pos)
        self.cancel_button.check_hover(mouse_pos)
        
        # 检查按钮点击
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.confirm_button.rect.collidepoint(mouse_pos):
                self.result = True
                return self.result
            elif self.cancel_button.rect.collidepoint(mouse_pos):
                self.result = False
                return self.result
        
        return None

class CampSelectionScreen:
    """阵营选择界面，让玩家选择执红方还是黑方"""
    
    def __init__(self):
        # 初始化窗口尺寸和模式
        self.window_width = DEFAULT_WINDOW_WIDTH
        self.window_height = DEFAULT_WINDOW_HEIGHT
        self.is_fullscreen = False
        self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        pygame.display.set_caption("中国象棋 - 选择阵营")
        
        self.update_layout()
        self.selected_camp = None
        
    def update_layout(self):
        """根据当前窗口尺寸更新布局"""
        button_width = 300
        button_height = 80
        button_spacing = 40
        center_x = self.window_width // 2
        center_y = self.window_height // 2
        
        # 创建按钮
        self.red_button = Button(
            center_x - button_width // 2,
            center_y - button_height - button_spacing // 2,
            button_width,
            button_height,
            "执红先行",
            32
        )
        
        self.black_button = Button(
            center_x - button_width // 2,
            center_y + button_spacing // 2,
            button_width,
            button_height,
            "执黑后行",
            32
        )
    
    def toggle_fullscreen(self):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        
        if self.is_fullscreen:
            # 获取显示器信息
            info = pygame.display.Info()
            # 保存窗口模式的尺寸
            self.windowed_size = (self.window_width, self.window_height)
            # 切换到全屏模式
            self.screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
            self.window_width = info.current_w
            self.window_height = info.current_h
        else:
            # 恢复窗口模式
            self.window_width, self.window_height = self.windowed_size
            self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        
        # 更新布局
        self.update_layout()
        
    def handle_resize(self, new_size):
        """处理窗口大小变化"""
        self.window_width, self.window_height = new_size
        # 更新布局
        self.update_layout()
        
    def run(self):
        """运行阵营选择界面"""
        clock = pygame.time.Clock()
        
        while self.selected_camp is None:
            mouse_pos = pygame.mouse.get_pos()
            
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                
                # 处理窗口大小变化
                if event.type == pygame.VIDEORESIZE:
                    if not self.is_fullscreen:  # 只在窗口模式下处理大小变化
                        self.handle_resize((event.w, event.h))
                
                # 处理键盘事件
                if event.type == pygame.KEYDOWN:
                    # F11或Alt+Enter切换全屏
                    if event.key == pygame.K_F11 or (
                        event.key == pygame.K_RETURN and 
                        pygame.key.get_mods() & pygame.KMOD_ALT
                    ):
                        self.toggle_fullscreen()
                
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.red_button.is_clicked(mouse_pos, event):
                        self.selected_camp = CAMP_RED
                    elif self.black_button.is_clicked(mouse_pos, event):
                        self.selected_camp = CAMP_BLACK
            
            # 更新按钮悬停状态
            self.red_button.check_hover(mouse_pos)
            self.black_button.check_hover(mouse_pos)
            
            # 绘制界面
            self.draw()
            pygame.display.flip()
            clock.tick(FPS)
        
        return self.selected_camp
    
    def draw(self):
        """绘制选择界面"""
        # 使用统一的背景绘制函数
        draw_background(self.screen)
        
        # 绘制标题
        title_font = pygame.font.SysFont('SimHei', 48)
        title_text = "选择您的阵营"
        title_surface = title_font.render(title_text, True, BLACK)
        title_rect = title_surface.get_rect(center=(self.window_width//2, 150))
        self.screen.blit(title_surface, title_rect)
        
        # 绘制提示文字
        hint_font = pygame.font.SysFont('SimHei', 24)
        hint_text = "在中国象棋中，红方先行"
        hint_surface = hint_font.render(hint_text, True, BLACK)
        hint_rect = hint_surface.get_rect(center=(self.window_width//2, 200))
        self.screen.blit(hint_surface, hint_rect)
        
        # 绘制金色装饰线
        line_y = title_rect.bottom + 40
        pygame.draw.line(
            self.screen, 
            GOLD, 
            (self.window_width//4, line_y), 
            (self.window_width*3//4, line_y), 
            3
        )
        
        # 绘制按钮
        self.red_button.draw(self.screen)
        self.black_button.draw(self.screen)

class ChessGame:
    def __init__(self, game_mode=MODE_PVP, player_camp=CAMP_RED, ai_difficulty="medium"):
        """初始化游戏
        
        Args:
            game_mode: 游戏模式，可选 MODE_PVP(人人对战) 或 MODE_PVC(人机对战)
            player_camp: 玩家阵营，可选 CAMP_RED(执红) 或 CAMP_BLACK(执黑)
            ai_difficulty: AI难度，可选 'easy', 'medium', 'hard'
        """
        # 初始化窗口尺寸和模式
        self.window_width = DEFAULT_WINDOW_WIDTH
        self.window_height = DEFAULT_WINDOW_HEIGHT
        self.is_fullscreen = False
        self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        pygame.display.set_caption("中国象棋")
        self.clock = pygame.time.Clock()
        
        # 创建棋盘和游戏状态
        self.update_layout()  # 初始化布局
        self.game_state = GameState()
        
        self.selected_piece = None
        self.game_mode = game_mode
        self.player_camp = player_camp  # 玩家阵营
        self.popup = None
        self.confirm_dialog = None  # 确认对话框
        self.ai_thinking = False  # AI是否正在思考
        self.ai_think_start_time = 0  # AI开始思考的时间
        self.ai_timeout = 3000  # AI思考超时时间(毫秒)
        
        # 记录上一步走法，用于显示
        self.last_move = None  # 格式为 (from_row, from_col, to_row, to_col)
        self.last_move_notation = ""  # 上一步走法的中文表示
        
        # 如果是人机对战，初始化AI
        self.ai = None
        if self.game_mode == MODE_PVC:
            from chess_ai import ChessAI
            ai_color = "black" if player_camp == CAMP_RED else "red"
            self.ai = ChessAI(difficulty=ai_difficulty, ai_color=ai_color)
            
        # 创建全屏切换按钮
        self.fullscreen_button = Button(
            self.window_width - 50,  # 右上角
            10, 
            40, 
            30, 
            "全屏", 
            14
        )
        
        # 如果是人机对战且AI先行，设置延迟启动AI
        if self.game_mode == MODE_PVC and self.game_state.player_turn != self.player_camp:
            pygame.time.set_timer(pygame.USEREVENT + 1, 800)  # 延迟800毫秒后AI行动
            self.ai_thinking = True
            
    def update_layout(self):
        """根据当前窗口尺寸更新布局"""
        # 计算左侧面板宽度和棋盘边距
        self.left_panel_width = int(LEFT_PANEL_WIDTH_RATIO * self.window_width)
        self.board_margin_top = int(BOARD_MARGIN_TOP_RATIO * self.window_height)
        
        # 更新棋盘
        self.board = ChessBoard(
            self.window_width - self.left_panel_width, 
            self.window_height, 
            self.left_panel_width, 
            self.board_margin_top
        )
        
        # 更新按钮位置
        button_width = 120
        button_height = 40
        button_y = self.window_height - 60
        
        # 更新返回按钮位置
        self.back_button = Button(
            self.left_panel_width + 80, 
            button_y, 
            button_width, 
            button_height, 
            "返回", 
            22
        )
        
        # 更新悔棋按钮位置
        self.undo_button = Button(
            self.window_width - button_width - 80, 
            button_y, 
            button_width, 
            button_height, 
            "悔棋", 
            22
        )
        
        # 更新全屏按钮位置
        self.fullscreen_button = Button(
            self.window_width - 50, 
            10, 
            40, 
            30, 
            "全屏" if not self.is_fullscreen else "退出", 
            14
        )
        
        # 更新头像位置
        avatar_radius = 40
        panel_center_x = self.left_panel_width // 2
        black_y = self.window_height // 3 - 50
        red_y = self.window_height * 2 // 3
        
        # 创建头像
        self.black_avatar = Avatar(panel_center_x, black_y, avatar_radius, (245, 245, 235), "黑方", False)
        self.red_avatar = Avatar(panel_center_x, red_y, avatar_radius, (255, 255, 240), "红方", True)
        
        # 设置当前玩家的头像为活跃状态
        if hasattr(self, 'game_state'):
            is_red_turn = self.game_state.player_turn == "red"
            self.red_avatar.set_active(is_red_turn)
            self.black_avatar.set_active(not is_red_turn)
            
        # 计时器的字体
        self.timer_font = pygame.font.SysFont('SimHei', 18)
    
    def toggle_fullscreen(self):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        
        if self.is_fullscreen:
            # 获取显示器信息
            info = pygame.display.Info()
            # 保存窗口模式的尺寸
            self.windowed_size = (self.window_width, self.window_height)
            # 切换到全屏模式
            self.screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
            self.window_width = info.current_w
            self.window_height = info.current_h
        else:
            # 恢复窗口模式
            self.window_width, self.window_height = self.windowed_size
            self.screen = pygame.display.set_mode((self.window_width, self.window_height), pygame.RESIZABLE)
        
        # 更新布局
        self.update_layout()
        
    def handle_resize(self, new_size):
        """处理窗口大小变化"""
        self.window_width, self.window_height = new_size
        # 更新布局
        self.update_layout()

    def run(self):
        """游戏主循环"""
        while True:
            mouse_pos = pygame.mouse.get_pos()
            current_time = pygame.time.get_ticks()
            
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                
                # 处理窗口大小变化
                if event.type == pygame.VIDEORESIZE:
                    if not self.is_fullscreen:  # 只在窗口模式下处理大小变化
                        self.handle_resize((event.w, event.h))
                
                # 处理AI移动的计时器事件
                if event.type == pygame.USEREVENT + 1:
                    self.make_ai_move()
                    pygame.time.set_timer(pygame.USEREVENT + 1, 0)  # 停止计时器
                
                # 处理悔棋后解除AI思考状态的延迟事件
                if event.type == pygame.USEREVENT + 2:
                    self.ai_thinking = False
                    pygame.time.set_timer(pygame.USEREVENT + 2, 0)  # 停止计时器
                
                # 处理键盘事件
                if event.type == pygame.KEYDOWN:
                    # F11或Alt+Enter切换全屏
                    if event.key == pygame.K_F11 or (
                        event.key == pygame.K_RETURN and 
                        pygame.key.get_mods() & pygame.KMOD_ALT
                    ):
                        self.toggle_fullscreen()
                
                # 如果有确认对话框，优先处理它的事件
                if self.confirm_dialog:
                    result = self.confirm_dialog.handle_event(event, mouse_pos)
                    if result is not None:  # 用户已做出选择
                        if result:  # 确认
                            self.confirm_dialog = None
                            return "back_to_menu"
                        else:  # 取消
                            self.confirm_dialog = None
                
                # 如果游戏结束，处理弹窗事件
                elif self.game_state.game_over and self.popup:
                    if self.popup.handle_event(event, mouse_pos):
                        self.__init__(self.game_mode, self.player_camp)  # 重置游戏，保持相同模式和阵营
                
                # 如果游戏未结束，处理鼠标点击
                elif not self.game_state.game_over:
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        # 检查是否点击了全屏按钮
                        if self.fullscreen_button.is_clicked(mouse_pos, event):
                            self.toggle_fullscreen()
                        # 检查是否点击了返回按钮
                        elif self.back_button.is_clicked(mouse_pos, event):
                            # 显示确认对话框而不是直接返回
                            self.confirm_dialog = ConfirmDialog(
                                400, 200, "是否要返回主菜单？\n这将丢失您的当前对局信息。"
                            )
                        # 检查是否点击了悔棋按钮
                        elif self.undo_button.is_clicked(mouse_pos, event):
                            self.handle_undo()
                        # 处理棋子操作，只有在当前回合是玩家回合时才处理
                        elif not self.ai_thinking and (self.game_mode == MODE_PVP or 
                              self.game_state.player_turn == self.player_camp):
                            self.handle_click(mouse_pos)
            
            # 检查AI是否思考超时
            if self.ai_thinking and current_time - self.ai_think_start_time > self.ai_timeout:
                # AI思考超时，强制结束思考
                print("AI思考超时，强制结束")
                self.ai_thinking = False
                pygame.time.set_timer(pygame.USEREVENT + 1, 0)  # 停止计时器
                
                # 如果是人机模式且轮到AI，随机走一步
                if self.game_mode == MODE_PVC and self.game_state.player_turn != self.player_camp:
                    self.make_random_ai_move()
            
            # 更新按钮的悬停状态
            self.undo_button.check_hover(mouse_pos)
            self.back_button.check_hover(mouse_pos)
            self.fullscreen_button.check_hover(mouse_pos)
            
            # 检查是否需要触发AI移动（例如游戏开始或重新开始后）
            if (self.game_mode == MODE_PVC and 
                not self.game_state.game_over and 
                self.game_state.player_turn != self.player_camp and
                not self.ai_thinking):
                self.schedule_ai_move()
            
            # 绘制画面
            self.draw(mouse_pos)
            pygame.display.flip()
            self.clock.tick(FPS)

    def draw(self, mouse_pos):
        """绘制游戏界面"""
        # 使用统一的背景绘制函数
        draw_background(self.screen)
        
        # 绘制左侧面板背景 - 使用与主界面一致的纹理
        left_panel_rect = pygame.Rect(0, 0, self.left_panel_width, self.window_height)
        
        # 先绘制与主背景一致的纹理
        left_panel_surface = pygame.Surface((self.left_panel_width, self.window_height))
        draw_background(left_panel_surface)  # 使用相同的背景绘制函数
        
        # 稍微调亮左侧面板使其有区分度
        overlay = pygame.Surface((self.left_panel_width, self.window_height), pygame.SRCALPHA)
        overlay.fill((255, 255, 255, 30))  # 半透明白色覆盖，轻微增亮
        left_panel_surface.blit(overlay, (0, 0))
        
        # 应用到主界面
        self.screen.blit(left_panel_surface, (0, 0))
        
        # 添加分隔线
        pygame.draw.line(self.screen, PANEL_BORDER, (self.left_panel_width, 0), 
                        (self.left_panel_width, self.window_height), 2)
        
        # 绘制棋盘和棋子 - 先绘制这些
        self.board.draw(self.screen, self.game_state.pieces)
        
        # 如果有上一步走法，在棋盘上标记出来
        if self.last_move:
            from_row, from_col, to_row, to_col = self.last_move
            self.board.highlight_last_move(self.screen, from_row, from_col, to_row, to_col)
        
        # 检查是否需要显示将军动画 - 在棋子之上显示动画
        if self.game_state.should_show_check_animation():
            king_pos = self.game_state.get_checked_king_position()
            if king_pos:
                self.board.draw_check_animation(self.screen, king_pos)
        
        # 绘制游戏信息面板
        self.draw_info_panel()
        
        # 绘制悔棋按钮和返回按钮
        self.undo_button.draw(self.screen)
        self.back_button.draw(self.screen)
        self.fullscreen_button.draw(self.screen)
        
        # 绘制玩家头像
        self.red_avatar.draw(self.screen)
        self.black_avatar.draw(self.screen)
        
        # 绘制计时器信息
        self.draw_timers()
        
        # 在左侧面板中添加VS标志
        vs_font = pygame.font.SysFont('SimHei', 36, bold=True)
        vs_text = "VS"
        vs_surface = vs_font.render(vs_text, True, (100, 100, 100))
        vs_rect = vs_surface.get_rect(center=(self.left_panel_width // 2, self.window_height // 2))
        self.screen.blit(vs_surface, vs_rect)
        
        # 如果有上一步走法的记录，显示它
        if self.last_move_notation:
            move_font = pygame.font.SysFont('SimHei', 18)
            move_text = f"上一步: {self.last_move_notation}"
            move_surface = move_font.render(move_text, True, BLACK)
            # 显示在左侧面板底部
            move_rect = move_surface.get_rect(center=(self.left_panel_width // 2, self.window_height - 80))
            self.screen.blit(move_surface, move_rect)
        
        # 如果是人机模式，显示模式和阵营提示
        if self.game_mode == MODE_PVC:
            mode_font = pygame.font.SysFont('SimHei', 18)
            if self.player_camp == CAMP_RED:
                mode_text = "人机对战模式 - 您执红方"
            else:
                mode_text = "人机对战模式 - 您执黑方"
            mode_surface = mode_font.render(mode_text, True, BLACK)
            self.screen.blit(mode_surface, (self.left_panel_width + (self.window_width - self.left_panel_width)//2 - mode_surface.get_width()//2, 15))
            
            # 如果AI正在思考，显示提示
            if self.ai_thinking:
                thinking_font = pygame.font.SysFont('SimHei', 24)
                thinking_text = "电脑思考中..."
                thinking_surface = thinking_font.render(thinking_text, True, RED)
                thinking_rect = thinking_surface.get_rect(center=(self.window_width//2, 45))
                self.screen.blit(thinking_surface, thinking_rect)
        
        # 如果游戏结束，显示弹窗
        if self.game_state.game_over and self.popup:
            self.popup.draw(self.screen)
        
        # 如果有确认对话框，显示它
        if self.confirm_dialog:
            self.confirm_dialog.draw(self.screen)
    
    def draw_timers(self):
        """绘制计时器信息"""
        # 获取当前的时间状态
        red_time, black_time = self.game_state.update_times()
        total_time = self.game_state.total_time
        
        # 转换为分钟:秒格式
        red_time_str = f"{int(red_time//60):02}:{int(red_time%60):02}"
        black_time_str = f"{int(black_time//60):02}:{int(black_time%60):02}"
        total_time_str = f"{int(total_time//60):02}:{int(total_time%60):02}"
        
        # 绘制红方时间 - 在红方头像下方
        red_time_surface = self.timer_font.render(f"用时: {red_time_str}", True, RED)
        red_time_rect = red_time_surface.get_rect(
            center=(self.left_panel_width // 2, self.red_avatar.y + self.red_avatar.radius + 50)
        )
        self.screen.blit(red_time_surface, red_time_rect)
        
        # 绘制黑方时间 - 在黑方头像下方
        black_time_surface = self.timer_font.render(f"用时: {black_time_str}", True, BLACK)
        black_time_rect = black_time_surface.get_rect(
            center=(self.left_panel_width // 2, self.black_avatar.y + self.black_avatar.radius + 50)
        )
        self.screen.blit(black_time_surface, black_time_rect)
        
        # 绘制总时间 - 在左侧面板顶部
        total_time_surface = self.timer_font.render(f"对局时长: {total_time_str}", True, BLACK)
        self.screen.blit(total_time_surface, (10, 10))
    
    def draw_info_panel(self):
        """绘制游戏信息面板"""
        # 当游戏进行中，在楚河汉界中央显示当前回合
        if not self.game_state.game_over:
            # 创建回合信息文本
            turn_color = RED if self.game_state.player_turn == "red" else BLACK
            turn_text = f"当前回合: {'红方' if self.game_state.player_turn == 'red' else '黑方'}"
            
            # 计算位置 - 在楚河汉界中央位置
            font = pygame.font.SysFont('SimHei', 30)
            text_surface = font.render(turn_text, True, turn_color)
            x = self.left_panel_width + (self.window_width - self.left_panel_width) // 2
            y = self.board_margin_top + 4.5 * (self.board.board_width / 8)  # 与楚河汉界在同一位置
            text_rect = text_surface.get_rect(center=(x, y))
            
            # 绘制带背景的文本，使其更加明显
            # 先画一个轻微半透明的背景
            padding = 10
            bg_rect = pygame.Rect(text_rect.left - padding, text_rect.top - padding, 
                                 text_rect.width + padding*2, text_rect.height + padding*2)
            bg_surface = pygame.Surface((bg_rect.width, bg_rect.height), pygame.SRCALPHA)
            bg_surface.fill((255, 255, 255, 180))  # 半透明白色背景
            self.screen.blit(bg_surface, (bg_rect.left, bg_rect.top))
            
            # 然后绘制文本
            self.screen.blit(text_surface, text_rect)
    
    def handle_click(self, pos):
        """处理鼠标点击事件"""
        # 获取点击的棋盘位置
        grid_pos = self.board.get_grid_position(pos)
        if not grid_pos:
            return
            
        row, col = grid_pos
        
        # 选择棋子或移动棋子
        if self.selected_piece is None:
            # 尝试选择棋子
            piece = self.game_state.get_piece_at(row, col)
            if piece and piece.color == self.game_state.player_turn:
                self.selected_piece = (row, col)
                self.board.highlight_position(row, col)
                
                # 计算可能的移动位置
                possible_moves, capturable = self.game_state.calculate_possible_moves(row, col)
                self.board.set_possible_moves(possible_moves)
                self.board.set_capturable_positions(capturable)
        else:
            sel_row, sel_col = self.selected_piece
            
            # 检查是否点击了同一个棋子（取消选择）
            if sel_row == row and sel_col == col:
                self.selected_piece = None
                self.board.clear_highlights()
                return
                
            # 检查是否选择了另一个己方棋子（更换选择）
            new_piece = self.game_state.get_piece_at(row, col)
            if new_piece and new_piece.color == self.game_state.player_turn:
                self.selected_piece = (row, col)
                self.board.highlight_position(row, col)
                
                # 计算新选择棋子的可能移动
                possible_moves, capturable = self.game_state.calculate_possible_moves(row, col)
                self.board.set_possible_moves(possible_moves)
                self.board.set_capturable_positions(capturable)
                return
            
            # 已选择棋子，尝试移动
            captured_piece = self.game_state.get_piece_at(row, col)
            move_successful = self.game_state.move_piece(sel_row, sel_col, row, col)
            
            if move_successful:
                # 记录上一步走法
                self.last_move = (sel_row, sel_col, row, col)
                
                # 生成上一步走法的中文表示
                piece = self.game_state.get_piece_at(row, col)
                if piece:
                    self.last_move_notation = self.generate_move_notation(piece, sel_row, sel_col, row, col)
                
                # 播放移动音效
                if captured_piece:
                    try:
                        CAPTURE_SOUND.play()
                    except:
                        pass
                else:
                    try:
                        MOVE_SOUND.play()
                    except:
                        pass
                
                # 更新头像状态
                self.update_avatars()
                
                # 如果新的状态是将军，播放将军音效
                if self.game_state.is_check:
                    try:
                        CHECK_SOUND.play()
                    except:
                        pass
                
                # 检查游戏是否结束
                if self.game_state.game_over:
                    winner_text = self.game_state.get_winner_text()
                    
                    # 更新时间数据，确保获取最终值
                    red_time, black_time = self.game_state.update_times()
                    total_time = self.game_state.total_time
                    
                    # 创建弹窗并传入时间信息
                    self.popup = PopupDialog(
                        400, 320,  # 增加高度以适应更多内容
                        winner_text,
                        total_time,
                        red_time,
                        black_time
                    )
                # 如果是人机模式且轮到AI走子，触发AI移动
                elif self.game_mode == MODE_PVC and self.game_state.player_turn != self.player_camp:
                    self.schedule_ai_move()
            
            # 无论如何都取消选择状态
            self.selected_piece = None
            self.board.clear_highlights()
    
    def generate_move_notation(self, piece, from_row, from_col, to_row, to_col):
        """生成走法的中文表示，如"炮二平五"、"马8进7"等"""
        from chess_pieces import King, Shi, Xiang, Ma, Ju, Pao, Pawn
        
        piece_names = {
            "king": "帅" if piece.color == "red" else "将",
            "advisor": "仕" if piece.color == "red" else "士",
            "elephant": "相" if piece.color == "red" else "象",
            "horse": "马",
            "rook": "車",
            "cannon": "炮",
            "pawn": "兵" if piece.color == "red" else "卒"
        }
        
        # 获取棋子名称
        if isinstance(piece, King):
            piece_name = piece_names["king"]
        elif isinstance(piece, Shi):
            piece_name = piece_names["advisor"]
        elif isinstance(piece, Xiang):
            piece_name = piece_names["elephant"]
        elif isinstance(piece, Ma):
            piece_name = piece_names["horse"]
        elif isinstance(piece, Ju):
            piece_name = piece_names["rook"]
        elif isinstance(piece, Pao):
            piece_name = piece_names["cannon"]
        elif isinstance(piece, Pawn):
            piece_name = piece_names["pawn"]
        else:
            piece_name = piece.name  # 直接使用棋子名称
        
        # 转换列数为中文数字或数字 - 从右至左标识
        # 红方用一至九标识，黑方用1-9标识
        col_names_red = ["一", "二", "三", "四", "五", "六", "七", "八", "九"]
        col_names_black = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
        
        # 根据棋子颜色选择合适的列名表示
        col_names = col_names_red if piece.color == "red" else col_names_black
        
        # 计算棋盘坐标到列标识的映射（从右到左）
        col_index = 8 - from_col  # 从右到左映射
        from_col_name = col_names[col_index]
        
        # 判断移动方向
        direction = ""
        if to_row < from_row:  # 向上移动
            direction = "进" if piece.color == "red" else "退"
        elif to_row > from_row:  # 向下移动
            direction = "退" if piece.color == "red" else "进"
        else:  # 水平移动
            direction = "平"
        
        # 获取目标位置
        if direction == "平":
            # 平移表示目标列
            to_col_index = 8 - to_col  # 从右到左映射
            to_col_name = col_names[to_col_index]
            notation = f"{piece_name}{from_col_name}{direction}{to_col_name}"
        else:
            # 进退表示移动的距离或目标列
            # 检查是否是马、象、士
            is_diagonal_piece = (isinstance(piece, Ma) or isinstance(piece, Xiang) or 
                               isinstance(piece, Shi))
            
            if is_diagonal_piece:
                # 马、象、士用目标列表示
                to_col_index = 8 - to_col  # 从右到左映射
                to_col_name = col_names[to_col_index]
                notation = f"{piece_name}{from_col_name}{direction}{to_col_name}"
            else:
                # 其他棋子用移动距离表示
                distance = abs(from_row - to_row)
                if piece.color == "black" and direction == "进":
                    # 黑方前进和红方后退是增加行号
                    distance_str = col_names_black[distance-1]
                elif piece.color == "black" and direction == "退":
                    # 黑方后退和红方前进是减少行号
                    distance_str = col_names_black[distance-1]
                else:
                    # 红方使用汉字数字表示距离
                    distance_str = ["一", "二", "三", "四", "五", "六", "七", "八", "九"][distance-1]
                notation = f"{piece_name}{from_col_name}{direction}{distance_str}"
        
        return notation
    
    def handle_undo(self):
        """处理悔棋操作"""
        # 如果AI正在思考，不允许悔棋
        if self.ai_thinking:
            return False
        
        # 如果游戏已经结束，先清除状态
        if self.game_state.game_over:
            self.popup = None
            self.game_state.game_over = False
        
        if self.game_mode == MODE_PVP:
            # 人人模式直接悔棋
            if self.game_state.undo_move():
                # 悔棋成功
                self.selected_piece = None
                self.board.clear_highlights()
                self.update_avatars()
                
                # 清除上一步记录
                self.last_move = None
                self.last_move_notation = ""
                
                # 如果还有移动历史，更新上一步记录
                if hasattr(self.game_state, 'move_history') and len(self.game_state.move_history) > 0:
                    last_history = self.game_state.move_history[-1]
                    if 'from_pos' in last_history and 'to_pos' in last_history:
                        from_row, from_col = last_history['from_pos']
                        to_row, to_col = last_history['to_pos']
                        self.last_move = (from_row, from_col, to_row, to_col)
                        piece = self.game_state.get_piece_at(to_row, to_col)
                        if piece:
                            self.last_move_notation = self.generate_move_notation(
                                piece, from_row, from_col, to_row, to_col
                            )
                
                return True
        else:  # 人机模式
            # 首先停止任何AI计时器
            pygame.time.set_timer(pygame.USEREVENT + 1, 0)
            pygame.time.set_timer(pygame.USEREVENT + 2, 0)
            self.ai_thinking = False
            
            # 移动历史为空，没有步骤可以悔棋
            if not hasattr(self.game_state, 'move_history') or len(self.game_state.move_history) == 0:
                return False
            
            # 判断当前是玩家回合还是AI回合
            is_player_turn = self.game_state.player_turn == self.player_camp
            
            if is_player_turn:
                # 玩家回合 - 需要悔两步（玩家和AI各一步）
                if len(self.game_state.move_history) >= 1:
                    # 至少有一步可以悔棋
                    self.game_state.undo_move()  # 悔掉玩家上一步
                    
                    # 如果还有更多步骤，尝试悔掉AI的上一步
                    if len(self.game_state.move_history) >= 1:
                        self.game_state.undo_move()  # 悔掉AI上一步
                    
                    self.selected_piece = None
                    self.board.clear_highlights()
                    self.update_avatars()
                    return True
            else:
                # AI回合 - 悔一步（AI刚下的或上一个玩家步骤）
                if len(self.game_state.move_history) >= 1:
                    self.game_state.undo_move()
                    self.selected_piece = None
                    self.board.clear_highlights()
                    self.update_avatars()
                    
                    # 如果悔棋后轮到AI行动，延迟1秒
                    if self.game_state.player_turn != self.player_camp:
                        self.ai_thinking = True
                        pygame.time.set_timer(pygame.USEREVENT + 2, 1000)
                    
                    return True
        
        return False

    def make_random_ai_move(self):
        """当AI思考超时时，执行随机移动"""
        if not self.ai or self.game_mode != MODE_PVC:
            return
        
        # 获取所有可能的移动
        valid_moves = []
        ai_color = "black" if self.player_camp == CAMP_RED else "red"
        
        for piece in self.game_state.pieces:
            if piece.color == ai_color:
                possible_moves, _ = self.game_state.calculate_possible_moves(piece.row, piece.col)
                for to_row, to_col in possible_moves:
                    valid_moves.append(((piece.row, piece.col), (to_row, to_col)))
        
        if valid_moves:
            # 随机选择一个移动
            from_pos, to_pos = random.choice(valid_moves)
            from_row, from_col = from_pos
            to_row, to_col = to_pos
            
            # 检查目标位置是否有棋子（吃子）
            target_piece = self.game_state.get_piece_at(to_row, to_col)
            
            # 执行移动
            self.game_state.move_piece(from_row, from_col, to_row, to_col)
            
            # 记录上一步走法
            self.last_move = (from_row, from_col, to_row, to_col)
            
            # 生成上一步走法的中文表示
            piece = self.game_state.get_piece_at(to_row, to_col)
            if piece:
                self.last_move_notation = self.generate_move_notation(piece, from_row, from_col, to_row, to_col)
            
            # 播放音效
            if target_piece:
                try:
                    CAPTURE_SOUND.play()
                except:
                    pass
            else:
                try:
                    MOVE_SOUND.play()
                except:
                    pass
            
            # 更新头像状态
            self.update_avatars()
            
            # 如果新的状态是将军，播放将军音效
            if self.game_state.is_check:
                try:
                    CHECK_SOUND.play()
                except:
                    pass
            
            # 检查游戏是否结束
            if self.game_state.game_over:
                winner_text = self.game_state.get_winner_text()
                
                # 更新时间数据，确保获取最终值
                red_time, black_time = self.game_state.update_times()
                total_time = self.game_state.total_time
                
                # 创建弹窗并传入时间信息
                self.popup = PopupDialog(
                    400, 320,  # 增加高度以适应更多内容
                    winner_text,
                    total_time,
                    red_time,
                    black_time
                )

    def update_avatars(self):
        """更新头像状态"""
        is_red_turn = self.game_state.player_turn == "red"
        self.red_avatar.set_active(is_red_turn)
        self.black_avatar.set_active(not is_red_turn)
        
        # 更新玩家标识
        if self.game_mode == MODE_PVC:
            if self.player_camp == CAMP_RED:
                self.red_avatar.player_name = "玩家"
                self.black_avatar.player_name = "电脑"
            else:
                self.red_avatar.player_name = "电脑"
                self.black_avatar.player_name = "玩家"
        else:
            self.red_avatar.player_name = "红方"
            self.black_avatar.player_name = "黑方"

    def schedule_ai_move(self):
        """安排AI移动"""
        self.ai_thinking = True
        self.ai_think_start_time = pygame.time.get_ticks()  # 记录AI开始思考的时间
        
        # 启动一个计时器延迟AI移动，使移动看起来更自然
        pygame.time.set_timer(pygame.USEREVENT + 1, 500)  # 延迟500毫秒
    
    def make_ai_move(self):
        """执行AI移动"""
        if not self.ai:
            self.ai_thinking = False
            return
        
        # 获取AI的最佳移动
        move = self.ai.get_move(self.game_state)
        
        if move:
            from_pos, to_pos = move
            from_row, from_col = from_pos
            to_row, to_col = to_pos
            
            # 检查目标位置是否有棋子（吃子）
            target_piece = self.game_state.get_piece_at(to_row, to_col)
            
            # 执行移动
            self.game_state.move_piece(from_row, from_col, to_row, to_col)
            
            # 记录上一步走法
            self.last_move = (from_row, from_col, to_row, to_col)
            
            # 生成上一步走法的中文表示
            piece = self.game_state.get_piece_at(to_row, to_col)
            if piece:
                self.last_move_notation = self.generate_move_notation(piece, from_row, from_col, to_row, to_col)
            
            # 播放音效
            if target_piece:
                try:
                    CAPTURE_SOUND.play()
                except:
                    pass
            else:
                try:
                    MOVE_SOUND.play()
                except:
                    pass
            
            # 如果新的状态是将军，播放将军音效
            if self.game_state.is_check:
                try:
                    CHECK_SOUND.play()
                except:
                    pass
            
            # 更新头像状态
            self.update_avatars()
            
            # 检查游戏是否结束
            if self.game_state.game_over:
                winner_text = self.game_state.get_winner_text()
                
                # 更新时间数据，确保获取最终值
                red_time, black_time = self.game_state.update_times()
                total_time = self.game_state.total_time
                
                # 创建弹窗并传入时间信息
                self.popup = PopupDialog(
                    400, 320,  # 增加高度以适应更多内容
                    winner_text,
                    total_time,
                    red_time,
                    black_time
                )
        
        self.ai_thinking = False

def main():
    """主函数，处理游戏流程"""
    # 首先显示模式选择界面
    mode_screen = ModeSelectionScreen()
    game_mode = mode_screen.run()
    
    # 运行游戏循环
    while True:
        player_camp = CAMP_RED  # 默认玩家执红
        
        # 如果是人机对战模式，显示阵营选择界面
        if game_mode == MODE_PVC:
            camp_screen = CampSelectionScreen()
            player_camp = camp_screen.run()
        
        # 根据选择的模式和阵营创建游戏
        game = ChessGame(game_mode, player_camp)
        result = game.run()
        
        # 如果返回到菜单，重新显示模式选择界面
        if result == "back_to_menu":
            mode_screen = ModeSelectionScreen()
            game_mode = mode_screen.run()

if __name__ == "__main__":
    main() 